package demo.xlj.yuyi.studentapp.login;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import butterknife.BindView;
import butterknife.ButterKnife;
import demo.xlj.yuyi.studentapp.R;
import demo.xlj.yuyi.studentapp.base.BaseApplication;
import demo.xlj.yuyi.studentapp.base.BaseRxActivity;
import demo.xlj.yuyi.studentapp.bean.LoginBean;
import demo.xlj.yuyi.studentapp.dudaoyuan.DuDaoActivity;
import demo.xlj.yuyi.studentapp.greendao.UserDao;
import demo.xlj.yuyi.studentapp.qitabumen.QiTaActivity;
import demo.xlj.yuyi.studentapp.register.StudentMeetRegisterActivity;
import demo.xlj.yuyi.studentapp.retrofit.RetrofitClient;
import demo.xlj.yuyi.studentapp.rxjava.RxSchedulers;
import demo.xlj.yuyi.studentapp.shetuan.SheTActivity;
import demo.xlj.yuyi.studentapp.shetuanshencha.ShenCActivity;
import demo.xlj.yuyi.studentapp.utils.ActivityUtil;
import demo.xlj.yuyi.studentapp.utils.SharePerferencesUtils;
import demo.xlj.yuyi.studentapp.utils.ToastUtil;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import top.wefor.circularanim.CircularAnim;

/**
 * A login screen that offers login via email/password.
 */
public class StudentMeetLoginActivity extends BaseRxActivity {


    @BindView(R.id.editText_student_meet_login_name)
    EditText mEditTextStudentMeetLoginName;
    @BindView(R.id.editText_student_meet_login_password)
    EditText mEditTextStudentMeetLoginPassword;
    @BindView(R.id.email_sign_in_button)
    Button mEmailSignInButton;
    @BindView(R.id.progressBar_student_meet_login)
    ProgressBar mProgressBarStudentMeetLogin;
    @BindView(R.id.textView_student_meet_login)
    TextView mTextViewStudentMeetLogin;

    private String name;
    private String password;

    private UserDao mUserDao;

    private boolean isYou = false;

    private Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 11:
                    mEditTextStudentMeetLoginName.setText("");
                    mEditTextStudentMeetLoginPassword.setText("");
                    //查询的准备工作
                    mProgressBarStudentMeetLogin.setVisibility(View.VISIBLE);
                    addRxDestroy(RetrofitClient.getInstance(StudentMeetLoginActivity.this)
                            .getApiService()
                            .loginUser(name, password)
                            .compose(RxSchedulers.<LoginBean>io_main())
                            .subscribe(new Consumer<LoginBean>() {
                                @Override
                                public void accept(@NonNull LoginBean loginBean) throws Exception {
                                    if (loginBean.getStatus() == 10011) {
                                        mProgressBarStudentMeetLogin.setVisibility(View.INVISIBLE);
                                        ToastUtil.success(StudentMeetLoginActivity.this, "登录成功", true, true);
                                        String[] key = {"isWho", "name", "pwd", "username", "identity"};
                                        String[] value = {loginBean.getInfo().getIdentity() + ""
                                                , loginBean.getInfo().getUserid() + ""
                                                , loginBean.getInfo().getPwd() + ""
                                                , loginBean.getInfo().getUsername() + ""
                                                , loginBean.getInfo().getIdentity() + ""};

                                        SharePerferencesUtils.putMore(StudentMeetLoginActivity.this, key, value, 0);
                                        int code = loginBean.getInfo().getIdentity();
                                        if (code == 0) {
                                            ActivityUtil.openActivityFromBottomToTop(StudentMeetLoginActivity.this, DuDaoActivity.class);
                                        } else if (code == 1) {
                                            ActivityUtil.openActivityFromBottomToTop(StudentMeetLoginActivity.this, ShenCActivity.class);
                                        } else if (code == 2) {
                                            ActivityUtil.openActivityFromBottomToTop(StudentMeetLoginActivity.this, QiTaActivity.class);
                                        } else if (code == 3) {
                                            ActivityUtil.openActivityFromBottomToTop(StudentMeetLoginActivity.this, SheTActivity.class);
                                        }
                                        StudentMeetLoginActivity.this.finish();
                                    } else {
                                        ToastUtil.warning(StudentMeetLoginActivity.this, "登录失败:" + loginBean.getInfo().getError(), true, true);
                                        myHandler.sendEmptyMessage(33);
                                    }
                                }
                            }, new Consumer<Throwable>() {
                                @Override
                                public void accept(@NonNull Throwable throwable) throws Exception {
                                    ToastUtil.error(StudentMeetLoginActivity.this, "throwable:" + throwable.getMessage(), true, true);
                                    myHandler.sendEmptyMessage(33);
                                }
                            }));
                    break;
                //                    //查询数据库
//                    List<User> mList = mUserDao.loadAll();
//                    for (int i = 0; i < mList.size(); i++) {
//                        if (name.equals(mList.get(i).getName())) {
//                            isYou = true;
//                            if (password.equals(mList.get(i).getPassword())) {
//                                //说明对应了，登录成功了,添加到sp文件中
//                                int code = mList.get(i).getCode();
//                                ToastUtil.success(StudentMeetLoginActivity.this,"登录成功",true,true);
//                                String [] key_Test = {"isWho","name","password"};
//                                Object [] value_Test = {code,name,password};
//                                SharePerferencesUtils.putMore(StudentMeetLoginActivity.this,key_Test,value_Test,0);
//                                if (code == 0){
//                                    ActivityUtil.openActivityFromBottomToTop(StudentMeetLoginActivity.this, DuDaoYuanActivity.class);
//                                }else if (code == 1){
//                                    ActivityUtil.openActivityFromBottomToTop(StudentMeetLoginActivity.this, SheTuanShenChaBuActivity.class);
//                                }else if (code ==2){
//                                    ActivityUtil.openActivityFromBottomToTop(StudentMeetLoginActivity.this, OtherBuMenActivity.class);
//                                }else if (code == 3){
//                                    ActivityUtil.openActivityFromBottomToTop(StudentMeetLoginActivity.this, SheTuanActivity.class);
//                                }
//                                StudentMeetLoginActivity.this.finish();
//                                return;
//                            } else {
//                                //说明名字对应了，但是密码不对
//                                ToastUtil.warning(StudentMeetLoginActivity.this, "密码不对哦", true, true);
//                                myHandler.sendEmptyMessage(33);
//                                return;
//                            }
//                        }
//                    }
//                    if (!isYou){
//                        ToastUtil.info(StudentMeetLoginActivity.this,"这个账号暂未注册，马上注册一个吧", true,true);
//                        myHandler.sendEmptyMessage(33);
//                    }


                case 33:
                    //说明前面输入的不对，那么需要用户再重新输入了
                    mProgressBarStudentMeetLogin.setVisibility(View.INVISIBLE);
                    CircularAnim.show(mEmailSignInButton).go();

                    break;

                default:
                    ToastUtil.warning(StudentMeetLoginActivity.this, "请重启应用", true, true);
                    break;


            }


        }
    };


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_student_meet_login);
        ButterKnife.bind(this);
        initListener();
        mUserDao = BaseApplication.instances.getDaoSession().getUserDao();
    }

    /**
     * 完成初始化监听等一系列方法
     */
    private void initListener() {

        mTextViewStudentMeetLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityUtil.openActivityFromLeftToRight(StudentMeetLoginActivity.this, StudentMeetRegisterActivity.class);
            }
        });
    }


    /***
     * 点击去登录
     * @param view
     */
    public void btn_student_meet_login_go(View view) {
        name = mEditTextStudentMeetLoginName.getText().toString();
        password = mEditTextStudentMeetLoginPassword.getText().toString();

        if (TextUtils.isEmpty(name)) {
            mEditTextStudentMeetLoginName.setError("用户名不能为空");
            return;
        }

        if (TextUtils.isEmpty(password)) {
            mEditTextStudentMeetLoginPassword.setError("密码不能为空");
            return;
        }


        if (name.length() < 6) {
            mEditTextStudentMeetLoginName.setError("用户名长度不够");
            return;
        }

        if (password.length() < 6) {
            mEditTextStudentMeetLoginPassword.setError("密码长度不够");
            return;
        }

        //开启动画
        CircularAnim.hide(mEmailSignInButton).go();

        myHandler.sendEmptyMessageDelayed(11, 618);


    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN)
        {

            if((System.currentTimeMillis()-exitTime) > 2000)  //System.currentTimeMillis()无论何时调用，肯定大于2000
            {
                Toast.makeText(getApplicationContext(), "再按一次退出程序",Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            }else
            {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }





}

